const PENDING = "pending";
const FULFILLED = "fulfilled";
const REJECTED = "rejected";
const Promise = function (executor) {
	if (!(executor instanceof Function)) {
		throw "executor类型错误！"
	}
	this.state = PENDING;// 状态
	this.result = undefined;// 状态值
	this.callback = [];
	// 更改状态为fulfilled,成功值为value
	const _onResolve = function (value) {
		// 如果状态被更改，那么不允许执行后续代码（状态只允许更改一次）
		if (this.state !== PENDING) return;
		this.state = FULFILLED;
		this.result = value;
		if(this.callback.length) this.callback.forEach(item=>item.onResolved())
	}
	// 更改状态为rejected,失败的值为value
	const _onReject = function (value) {
		if (this.state !== PENDING) return;
		this.state = REJECTED;
		this.result = value;
		if(this.callback.length) this.callback.forEach(item=>item.onRejected())
	}
	try {
		// 调用执行器函数
		executor(_onResolve.bind(this), _onReject.bind(this));
	} catch (value) {
		// _onReject.bind(this,value)();
		_onReject.call(this, value)
	}
	
};
Object.assign(Promise.prototype, {
	// onResolved:成功回调
	// onRejected:失败回调
	then(onResolved, onRejected) {
		// 如果onResolved不是函数，成功回调默认为value=>value
		if(!(onResolved instanceof Function)){
			onResolved = value=>value;
		}
		// 如果onRejected不是函数，失败回调默认值为reason=>{throw reason};
		if(!(onRejected instanceof Function)){
			onRejected = reason=>{
				throw reason;
			}
		}
		// this--->p
		return new Promise(function (resolve, reject) {
			const _common = function (cb) {
				setTimeout(() => {
					try {
						// 调用成功回调，成功回调的返回值会影响返回的Promise实例状态和值
						const value = cb(this.result);
						// value是否为Promise实例
						if (value instanceof Promise) {
							// 是,将then函数返回的Promise实例的状态以及值设置为与value的状态和值相同。
							value.then(resolve, reject);
						} else {
							// 不是Promise实例，将then函数返回的Promise实例设置为成功，值为value
							resolve(value);
						}
					} catch (err) {
						reject(err);
					}
				})
				
			}
			// 判断当前状态是否为成功
			if (this.state === FULFILLED) {
				_common.call(this, onResolved);
			} else if (this.state === REJECTED) {
				_common.call(this, onRejected);
			} else {
				// 状态未更改，执行器函数中拥有异步行为
				this.callback.push({
					onResolved:_common.bind(this,onResolved),
					onRejected:_common.bind(this,onRejected)
				})
			}
		}.bind(this))
	},
	catch() {
	
	}
});
export default Promise;